package wetalk.software.bupt.com.wetalk.view.activity;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jyt.message.Message;
import com.jyt.util.MySerializable;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import wetalk.software.bupt.com.wetalk.GloableParams;
import wetalk.software.bupt.com.wetalk.R;
import wetalk.software.bupt.com.wetalk.application.UserManager;
import wetalk.software.bupt.com.wetalk.communicate.AndroidClientService;
import wetalk.software.bupt.com.wetalk.listener.PushListener;
import wetalk.software.bupt.com.wetalk.model.po.User;
import wetalk.software.bupt.com.wetalk.util.SharePreferenceUtil;
import wetalk.software.bupt.com.wetalk.util.WeTalkConfig;
import wetalk.software.bupt.com.wetalk.view.dialog.CustomDialog;
import wetalk.software.bupt.com.wetalk.widget.ClearEditText;

import static android.content.ContentValues.TAG;
import static wetalk.software.bupt.com.wetalk.application.MyApplication.getContext;

public class UpdateEmailActivity extends BaseActivity {
    private IntentFilter intentFilter;
    private UserInfoReceiver modifyuserInfoReceiver;

    private TextView mEmail;//显示原始邮箱
    private TextView txtMiddle;//显示我
    private Intent intent;
    private RelativeLayout rvImgBack;//返回
    private ClearEditText mNewEmail;//显示新邮箱
    private RelativeLayout rvImgRight;//确认更改
    private AndroidClientService.SendBinder sendBinder;
    private CustomDialog customDialog;//请求修改邮箱网络加载
    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            sendBinder= (AndroidClientService.SendBinder) iBinder;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_email);
        initWidget();
        initModifyUserInfoBC();
        initEvent();

    }


    //初始化控件
    private void initWidget(){
        //客户端发送消息
        Intent bindIntent = new Intent(this, AndroidClientService.class);
        this.bindService(bindIntent, connection, BIND_AUTO_CREATE);

        rvImgBack=(RelativeLayout)findViewById(R.id.rv_img_back);
        txtMiddle=(TextView)findViewById(R.id.txt_title);
        rvImgRight=(RelativeLayout)findViewById(R.id.rv_img_right);
        mNewEmail=(ClearEditText) findViewById(R.id.et_email);
        mEmail = (TextView) findViewById(R.id.tv_original_emial);
        //中间文字“修改邮箱”
        txtMiddle.setText("更改邮箱");
        //显示用户原邮箱
        intent = getIntent();
        String data = intent.getStringExtra("extra_email");
        mEmail.setText("原邮箱："+ data);
    }

    /*点击事件*/
    private void initEvent() {
        //点击左侧布局事件
        rvImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });


        //点击确定布局事件
        rvImgRight.setOnClickListener(new View.OnClickListener() {
            @Override//
            public void onClick(View view) {
                String email=mNewEmail.getText().toString();
                if(email.equals(""))
                {
                    Toast.makeText(UpdateEmailActivity.this,"请正确输入邮箱，不可为空",Toast.LENGTH_SHORT).show();
                }
                else if(isEmail(email)==false)
                {
                    Toast.makeText(UpdateEmailActivity.this,"请正确输入邮箱格式",Toast.LENGTH_SHORT).show();
                }
                else {
                    modifyUser(email, new PushListener() {
                        @Override
                        public void onSuccess() {

                            Toast.makeText(UpdateEmailActivity.this, "发送成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFailure(int var1, String var2) {
                            Toast.makeText(UpdateEmailActivity.this, "发送失败", Toast.LENGTH_SHORT).show();
                        }
                    });

                    CustomDialog.getDialog(UpdateEmailActivity.this,"正在修改...").show();
                }
            }
        });


    }

    //验证是否为正确邮箱
    public static boolean isEmail(String email){
        if (null==email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    //发送修改消息
    public void modifyUser(String context, final PushListener pushCallback)  {
        User saveUser = UserManager.getInstance(this).getCurrentUser();
        final String targetId = "sys_userinfo";
        final String userId= saveUser.getUserID();
        final JSONObject json=new JSONObject();

        //读取原始密码
        SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(getContext(), "WeTalk_SP");
        String originalPs = sharePreferenceUtil.getValue("password");
        try {
            json.put("id",userId);
            json.put("phone",saveUser.getPhone());
            json.put("email",context);
            json.put("passwd",originalPs);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        Thread thread=new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] bs;
                bs = MySerializable.object_bytes(json.toString());

                Message msg = new Message(userId,targetId,"modifyUserInfo",bs);
                sendBinder.sendMessage(msg);
                Log.i(TAG, "send message: "+msg);
                //pushCallback.onSuccess();
            }
        });
        thread.start();

    }
    //注册广播接收器
    private void initModifyUserInfoBC(){
        //接收广播
        intentFilter=new IntentFilter(WeTalkConfig.BROADCAST_MODIFY_USER_INFO);
        modifyuserInfoReceiver=new UserInfoReceiver();
        registerReceiver(modifyuserInfoReceiver,intentFilter);

    }

    class UserInfoReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            CustomDialog.getDialog(UpdateEmailActivity.this,"正在修改...").close();
            String result=null;
            String content=intent.getStringExtra("result");
            String newEmail = mNewEmail.getText().toString();
            try {
                JSONObject json=new JSONObject(content);
                result=json.getString("result");
                if(result.equals("success")){
                    Toast.makeText(context, "修改成功", Toast.LENGTH_SHORT).show();
                    SharePreferenceUtil sharePreferenceUtil = new SharePreferenceUtil(context, "WeTalk_SP");
                    User user = (User)sharePreferenceUtil.readObject("user");
                    user.setEmail(newEmail);
                    sharePreferenceUtil.saveObject(user,"user");

                    GloableParams.EMAIL = mNewEmail.getText().toString();
                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(modifyuserInfoReceiver);
        unbindService(connection);
    }

}
